package com.bishe.app.modules.login;

import cn.hutool.json.JSONUtil;
import com.bishe.app.core.api.CommonResult;
import com.bishe.app.core.enums.IsDel;
import com.bishe.app.core.utils.AppRunnerUtils;
import com.bishe.app.modules.user.entity.User;
import com.bishe.app.modules.user.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created : 2024/3/13, 19:29
 *
 * @author : jeffrey.hu
 **/
@RestController
@RequestMapping("/admin")
public class AdminController {


    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/login")
    public CommonResult<String> token(@RequestBody User user) {
        User dbUser = userService.lambdaQuery()
                .eq(User::getName, user.getName())
                .eq(User::getPwd, user.getPwd())
                .eq(User::getIsDel, IsDel.N.getCode())
                .one();

        if (Objects.nonNull(dbUser)) {
            String token = UUID.randomUUID().toString();
            int expireSecond = 60 * 60 * 1;
            redisTemplate.opsForValue().set(token, JSONUtil.toJsonStr(dbUser), expireSecond, TimeUnit.SECONDS);
            return CommonResult.success(token);
        } else {
            return CommonResult.failed("用户名/密码错误");
        }
    }

    @PostMapping("/logout")
    public CommonResult<String> token() {
        String tk = AppRunnerUtils.token();
        redisTemplate.delete(tk);
        return CommonResult.success(null);
    }

}
